<template>
  <MenuPage>
    <template slot="search" v-if="false">
      <Button type="primary" ghost class="md-add-jh" @click="setname = true">
        创建
      </Button>
      <Input
        v-model.trim="imageModelInput"
        clearable
        placeholder="单位名称"
        style="width: 150px; margin-left: 15px"
      />
      <Input
        v-model.trim="inputStsy"
        clearable
        placeholder="系统名字"
        style="width: 150px; margin-left: 15px"
      />
    </template>
    <template slot="content">
      <Tabs :value="curIconTab" @on-click="changeTab">
        <TabPane
          :label="value.name"
          :name="key"
          v-for="(value, key) in logOption"
          :key="key"
        >
          <Row v-for="logo in value.logo" :key="logo.label" :gutter="24">
            <Col span="24">
              <!-- style="margin-bottom: 10px; display: flex" -->
              {{ logo.title }}:
              <Upload
                v-if="logo.type !== 'sysName'"
                action="/api/minio/upload?bucket=icon&visibility=company"
                :headers="uploadHeader"
                :ref="value.name + '_upload_' + logo.label"
                :show-upload-list="false"
                :format="logo.format"
                footer-hide
                :on-success="(res) => handleUploadSuccess(res, logo)"
                :on-format-error="(res) => handleFormatError(res, logo)"
                style="margin-bottom: 10px; display: inline-block"
              >
                <!-- :before-upload="(file) => beforeUpload(file, logo)" -->
                <Button icon="ios-cloud-upload-outline">上传系统LOGO</Button>
                <img :src="logo.file" alt="" class="sysLogo" />
              </Upload>
              <!-- :max-size="logo.size"  :on-exceeded-size="handleUploadSize"-->
              <Form
                v-if="logo.type == 'sysName'"
                :rules="ruleValidate"
                ref="sysName"
                :model="logo"
              >
                <FormItem prop="sysName">
                  <Input
                    v-model="logo.sysName"
                    placeholder="请输入登录页名称"
                    @on-enter="saveLogoImg(logo)"
                    style="width: 150px; margin-right: 10px"
                  />
                </FormItem>
              </Form>
              显示：
              <i-switch
                v-model="logo.remark"
                @on-change="changeRemark(logo)"
                :disabled="getDisabled(logo)"
                true-value="enable"
                false-value="disable"
              >
                <span slot="open">是</span>
                <span slot="close">否</span>
              </i-switch>
              <Button
                type="primary"
                ghost
                @click="deleteId(logo)"
                class="delete"
                v-if="false"
              >
                清除
              </Button>
            </Col>
            <Col span="24" style="margin-bottom: 5px">
              <p style="color: #ff9900">{{ logo.tip }}</p>
            </Col>
          </Row>
        </TabPane>
      </Tabs>
    </template>
</MenuPage>
</template>

<script>
import { queryLogoImg, saveLogoImg, updateLogoImg, deleteLogoImg ,getLogoImg} from '@/api/login'
import {mapState} from 'vuex'
import $ from 'jquery';
export default {
  components: {},
  data () {
    return {
      imageModelInput: '',
      inputStsy: '',
      curIconTab: 'designerSystem',
      remark: 'enable',
      logo:'',
      logOption: {
        designerSystem: {
          name: '设计系统',
          logo: [
            // { type: 'bottom', label: 1, title: '菜单底部LOGO设置', size: 1024, format: ['jpg', 'jpeg', 'png'], tip: '请上传jpg、png、jpeg格式图片，图片大小不能超过1M，推荐的图片尺寸为175（px）* 48（px），且背景色为透明色',sysType:'designer'  },
            { type: 'top', label: 4, title: '菜单顶部图标设置', size: 1024, format: ['jpg', 'jpeg', 'png'], tip: '请上传jpg、png、jpeg请上传jpg、png、jpeg格式图片，推荐的图片尺寸为 314（px）* 60（px）' ,sysType:'designer'},
            { type: 'url', label: 2, title: '导航URL图标设置', size: 20, format: ['ico'], tip: '请上传ico格式图标，推荐的图片尺寸为 32（px）* 32（px）',sysType:'designer' },
            // { type: 'sysName', label: 5, title: '登录页名称',sysType:'designer' },
          ]
        },
        experSystem: {
          name: '课件系统',
          logo: [
            // { type: 'bottom', label: 1, title: '菜单底部LOGO设置', size: 1024, format: ['jpg', 'jpeg', 'png'], tip: '请上传jpg、png、jpeg格式图片，图片大小不能超过1M，推荐的图片尺寸为175（px）* 48（px），且背景色为透明色', sysType: 'exp' },
            { type: 'top', label: 4, title: '菜单顶部图标设置', size: 1024, format: ['jpg', 'jpeg', 'png'], tip: '请上传jpg、png、jpeg请上传jpg、png、jpeg格式图片，推荐的图片尺寸为 314（px）* 60（px）', sysType: 'exp' },
            { type: 'url', label: 2, title: '导航URL图标设置', size: 20, format: ['ico'], tip: '请上传ico格式图标，推荐的图片尺寸为 32（px）* 32（px）', sysType: 'exp' },
            { type: 'report', label: 3, title: '报告图标', size: 1024, format: ['jpg', 'jpeg', 'png'], tip: '请上传jpg、png、jpeg格式图片，推荐背景色为透明色', sysType: 'exp' },
            // { type: 'sysName', label: 5, title: '登录页名称', sysType: 'exp' },
          ]
        },
      },
      setname: false,
       ruleValidate: {
        sysName: [
          { required:true, message: '请输入登录页名称', trigger: 'blur' }
        ],
      },
      uploadHeader: {
        Authorization: localStorage.token,
        Accept: '*/*'
      },
      logoList:[]
    }
  },
  watch: {},
  created () {},
  mounted () {
    this.queryLogoImg() // 设计师配置
    // this.getLogoImg() //  运维logo 配置
  },
  computed: {
    ...mapState('user', ['companyName']), 
    pageTitle () {
      //当前菜单显示名
      return this.$route.meta.title;
    },
  },
  methods: {
    getDisabled (logo) {
      let disabled = false
      if (logo.type == 'sysName' && !logo.sysName) {
        disabled = true
      } else if (logo.type !== 'sysName' && !logo.file) {
        disabled = true
      }
      return disabled;
    },
    changeTab (name) {
      this.curIconTab = name
      this.queryLogoImg()
    },
    changeRemark (logo) {
      let params = {
        logoType: logo.type,
        sysType: logo.sysType,
        id: logo.id,
        logo: logo.file,
        sysName: logo.sysName || '',
        hidden: logo.remark ? logo.remark : 'disable',
        level:'company'
      }
      if (params.logo) {
        params.logo = params.logo.substring(6)
      }
      console.log('===',params);
      updateLogoImg(params).then(res => {
        if (res.data.code == 1) {
          this.queryLogoImg()
        }
      })
    },
    handleUploadSuccess (res, logo) {
      if (res.code == 1) {
        logo.file = res.data
        this.saveLogoImg(logo)
      } else {
        this.$Message.error({
          content: res.message,
          duration: 2,
        });
      }
    },
    handleUploadSize() {
			// this.showTip = true;
			this.$Message.error({
				content: '文件大小不能超过指定值！',
				duration: 3
			});
		},
    handleFormatError (res,logo) {
      let format = logo.format.join('')
      this.$Message.error({
        content: `文件格式错误！请上传${format}类型图片`,
        duration: 3,
      });
    },
    // 添加
    saveLogoImg (logo) {
      let params = {
        logoType: logo.type,
        sysType: logo.sysType,
        id: logo.id,
        logo: logo.file,
        sysName: logo.sysName || '',
        hidden: logo.remark ? logo.remark : 'disable',
        level:'company'
      }
      if (!params.sysName) {
        delete params.sysName
      }
      let api = ''
      if (logo.id) {
        if (logo.file) {
          params.logo.replace('/files', '')
        }
        api = updateLogoImg
      } else {
        delete params.id
        api = saveLogoImg
      }
      api(params).then(res => {
        if (res.data.code == 1) {
          this.queryLogoImg()
        } else {
          this.$Message.warning('操作失败')
        }
      }).catch(error => {
        console.log('saveLogoImg ~ error:', error)
      })
    },
    deleteId (logo) {
      deleteLogoImg(logo.id).then(res => {
        if (res.data.code == 1) {
          this.queryLogoImg()
        }
      }).catch(errer => {
        this.$Message.warning('删除失败')
      })
    },

    // 获取数据
    queryLogoImg () {
      let sysType;
      if (this.curIconTab == 'experSystem') {
        sysType = 'exp';
      } else if (this.curIconTab == 'designerSystem') {
        sysType = 'designer';
      }
      queryLogoImg({ systemType: sysType }).then(res => {
        if (res.data.code == 1) {
          // this.getLogoImg() //  运维logo 配置
          this.logoList = res.data.data;
          if (sysType == 'exp') {
            this.logOption.experSystem.logo.forEach(logo => {
              this.$set(logo, 'remark', this.getLogoRemark(logo));
              this.$set(logo, 'file', this.getLogoSrc(logo));
              this.$set(logo, 'id', this.getId(logo));
              this.$set(logo, 'sysName', this.getTitle(logo));
            })
          } else if (sysType == 'designer') {
            this.logOption.designerSystem.logo.forEach(logo => {
              this.$set(logo, 'remark', this.getLogoRemark(logo));
              this.$set(logo, 'file', this.getLogoSrc(logo));
              this.$set(logo, 'id', this.getId(logo));
              this.$set(logo, 'sysName', this.getTitle(logo));
            })
          }
        } else {
           this.$Message.warning('获取数据失败')
        }
      }).catch(errer => {
         this.$Message.warning('获取数据失败')
      })
    },
    // 禁用设置
    getLogoRemark (logo) {
      if (this.logoList.length > 0) {
        if (this.logoList.filter(item => item.logoType == logo.type).length > 0) {
          return this.logoList.filter(item => item.logoType == logo.type)[0].hidden;
        } else {
          return 'disable'
        }
      }
    },
    // 图片
    getLogoSrc (logo) {
      if (this.logoList.length > 0) {
        if (this.logoList.filter(item => item.logoType == logo.type && item.logo != '').length > 0) {
          return '/files' + this.logoList.filter(item => item.logoType == logo.type)[0].logo;
        } else {
          return ''
        }
      }
    },
    // 获取id
    getId (logo) {
      if (this.logoList.length > 0) {
        if (this.logoList.filter(item => item.logoType == logo.type).length > 0) {
          return this.logoList.filter(item => item.logoType == logo.type)[0].id;
        } else {
          return ''
        }
      }
    },
    // 设置名称
    getTitle (logo) {
      if (this.logoList.length > 0) {
        if (this.logoList.filter(item => item.logoType == logo.type).length > 0) {
          return this.logoList.filter(item => item.logoType == logo.type)[0].sysName;
        } else {
          return ''
        }
      }
    },
    getLogoImg () {
       let sysType;
      if (this.curIconTab == 'experSystem') {
        sysType = 'exp';
      } else if (this.curIconTab == 'designerSystem') {
        sysType = 'designer';
      }
      getLogoImg({ systemType: sysType }).then(res => {
        if (res.data.code === 1) {
          let getData = res.data.data
          let bot = this.getBottom(getData, this.logoList, 'bottom')
          let top = this.getBottom(getData, this.logoList, 'top')
          let url = this.getBottom(getData, this.logoList, 'url')
          let name = this.getName(getData, this.logoList, 'sysName')
          console.log('====bot', bot);
          console.log('====top', top);
          console.log('====url', url);
          console.log('====name', name);
          if (url) {
            document.getElementById('favicon').setAttribute("href", url)
          } else {
            document.getElementById('favicon').setAttribute("href",url + '?v=' + Math.random() * 100)
          }
        }
      })
    },

    getBottom (data1, data2, type) {
      let img = ''
      if (data1.length > 0 || data2.length > 0) {
        let logoType1 = data1.filter(d => d.logoType == type) // 运维设计
        let logoType2 = data2.filter(d => d.logoType == type) // 单位设计
        if (logoType1.length > 0 && logoType2.length > 0) {
          if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo
          } else if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'disable') {
            img = '/files' + logoType1[0].logo
          } else if (logoType1[0].hidden == 'disable' && logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo
          } else if (logoType1[0].hidden == 'enable') {
            img = '/files' + logoType1[0].logo
          } else if (logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo
          } else {
            img = ''
          }
        } else if (logoType1.length > 0 && logoType2.length == 0) {
          if (logoType1[0].hidden == 'enable') {
            img = '/files' + logoType1[0].logo
          }
        } else if (logoType1.length == 0 && logoType2.length > 0) {
          if (logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo
          }
        }
      } else {
        img = ''
      }
      return img;
    },
    getName (data1, data2, type) {
      let name = ''
      let logoType1 = data1.filter(d => d.logoType == type) // 运维设计
      let logoType2 = data2.filter(d => d.logoType == type) // 单位设计

      if (logoType1.length > 0 && logoType2.length > 0) {
        if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName
        } else if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'disable') {
          name = logoType1[0].sysName
        } else if (logoType1[0].hidden == 'disable' && logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName
        } else if (logoType1[0].hidden == 'enable') {
          name = logoType1[0].sysName
        } else if (logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName
        } else {
          name = ''
        }
      } else if (logoType1.length > 0 && logoType2.length == 0) {
        if (logoType1[0].hidden == 'enable') {
          name = logoType1[0].sysName
        } else {
          name = ''
        }
      } else if (logoType1.length == 0 && logoType2.length > 0) {
        if (logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName
        } else {
          name = ''
        }
      } else {
        name = ''
      }
      return name;
    },

    async beforeUpload (file, logo) {
      console.log('🚀 ~ file: coSet.vue:167 ~ beforeUpload ~ file:', file)
      if (file.size > 1024 * 1024) {
        this.$Message.success({ content: '请选择小于1024 KB 的图片', duration: 3 })
        return
      } else {
        // let imgUlr = await this.fileToBase64Async(file) // 转64
        //  imgUlr = imgUlr.replace(/^data:image\/\w+;base64,/, '')
        let imgUlr = await this.fileToUrl(file)
        logo.path = imgUlr
        this.saveLogoImg(logo)
      }
    },
    // file转图片url
    fileToUrl (file) {
      if (window.createObjectURL) {
        return window.createObjectURL(file);
      } else if (window.URL) {
        return window.URL.createObjectURL(file);
      } else if (window.webkitURL) {
        return window.webkitURL.createObjectURL(file);
      }
      return null;
    },
    // file 转 64
    fileToBase64Async (file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          resolve(e.target.result);
        };
      });
    },

  },
  beforeDestroy () {}
}
</script>
<style scoped>
.sysLogo {
  display: inline-block;
  height: 30px;
  width: auto;
  vertical-align: middle;
  background: #ebeff6;
  margin-left: 10px;
}
.delete {
  height: 30px;
  width: auto;
  margin-left: 20px;
}
</style>
